<?php
namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Mockery\Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\RequestBackController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CheckController;
/**
    收款接口
*/
class GatheringController extends Controller{
    
    /*
    收款显示
    */
    public function ShowGathering($request){//当ProceedsEnd == 1完成收款不显示删除按钮 ProceedsEnd == 0时可显示删除按钮
        if(!CheckController::CheckUser($request)){
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
		$page = isset($pos['page']) ? $pos['page']  : 1;
        $pageSize = isset($pos['pageSize']) ? $pos['pageSize'] : 10;
        $offset = ($page - 1) * $pageSize;
        if(!CheckController::CheckParameter($pos,['CaseId','UserId'])){//案件id
            return RequestBackController::Structure(502);
        }else{
            $GatheringInfo = DB::connection('mysql_other')->table('yl_proceeds as p')->select('p.proceeds_id as ProceedsId','p.proceeds_count as ProceedsCount','p.proceeds_creater_id as ProceedsCreaterId','p.proceeds_created_time as ProceedsCreatedTime','p.case_id as CaseId','p.proceeds_results_id as ProceedsResultsId','p.proceeds_end_time as ProceedsEndTime','p.proceeds_end as ProceedsEnd','pr.proceeds_results_id as ProceedsResultsId','pr.proceeds_results_title as ProceedsResultsTitle')
                         ->join("yl_proceeds_results as pr",function($join){
                                $join->on('p.proceeds_results_id','pr.proceeds_results_id');
                            })
                        ->where('case_id',$pos['CaseId']);
                        $count = $GatheringInfo->count();
                        $GatheringInfo = $GatheringInfo->offset($offset)->limit($pageSize)
							->get()->map(function ($val){
                                    $val = (array)$val;
                                    return $val;
                                    })
                                    ->keyBy(function($item)
                                    {
                                        return $item['ProceedsId'];
                                    })
									->toArray();
			$sum_page = ceil($count / $pageSize);  //总页码
            if ($page > $sum_page && $sum_page > 0) {
                return RequestBackController::Structure(301);
            }else
            //print_r($GatheringInfo);
				if($GatheringInfo){
				$YetPay = 0;
				//合同收费金额总数
                    $CaseCount = DB::connection('mysql_other')->table('yl_case')
                                                        ->where('case_id',$pos['CaseId'])
                                                        ->first();

				foreach ($GatheringInfo as $k => $v) {
                    $GatheringInfo[$k]['ProceedsCreatedTime'] = date('Y年m月d日',$v['ProceedsCreatedTime']);
                    if($v['ProceedsEndTime'] == 0 || $v['ProceedsEndTime'] == null){
                        $GatheringInfo[$k]['ProceedsEndTime']='---';
                    }else{
                        $GatheringInfo[$k]['ProceedsEndTime'] = date('Y年m月d日',$v['ProceedsEndTime']);
                    }
					if($v['ProceedsEnd'] == 1){
                           $YetPay += $v['ProceedsCount'];
                    }
					
                }
					//print_r($GatheringInfo);die;
					$row['List'] =$GatheringInfo;
					$row['SumMoney'] = $CaseCount->case_pay_count;
					//已收合同金额
                    $row['YetPay'] = $YetPay;
                    //剩余应收金额
                    $RemainPay = $row['SumMoney'] - $YetPay;
                    $row['RemainPay'] = $RemainPay;
					$row['count'] = $count;
                //print_r($GatheringInfo);
                return RequestBackController::Structure(501,$row);
            }else{
                return RequestBackController::Structure(504);
            }
        }
    }
	
	/*
	添加收款信息
	*/
	  public function AddGathering($request){
        if(!CheckController::CheckUser($request)){
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        //UserWegeArr律师收款比例{UserId,WageCount}
        if(!CheckController::CheckParameter($pos,['CaseId','UserId','ProceedsCount','UserWegeArr','ProceedsResultsId'])){
			return RequestBackController::Structure(502);
		}else{
            $Purview = new PurviewController();
            $UserPurview = $Purview->PurviewVerdict($request,$pos['UserId']);
            if($UserPurview == 'All'){//管理员添加收款信息
                $foo = $pos['UserWegeArr'];
				$total = 0;
                foreach ($foo as $k1 => $v1) {//判断律师比列金额小于等于总金额
                      $total += $v1['WageCount'];
                }
                if($total > $pos['ProceedsCount']){
					return RequestBackController::Structure(405);
				}else{
                    $add = array();
                    $add['case_id']=$pos['CaseId'];
                    $add['proceeds_count']=$pos['ProceedsCount'];//收款金额
                    $add['proceeds_creater_id']=$pos['UserId'];//创建人员
                    $add['proceeds_created_time']=time();
                    $add['proceeds_results_id']=$pos['ProceedsResultsId'];//收款状态
                    $WageTotal = DB::connection('mysql_other')->table('yl_proceeds')->insert($add);
                    if($WageTotal){
                        $MaxId = DB::connection('mysql_other')->table('yl_proceeds')->max('proceeds_id');
                        $arr = array();
                        foreach ($foo as $k => $v){
                            $arr['case_id'] = $pos['CaseId'];
                            $arr['user_id'] = $v['UserId'];//UserWegeArr
                            $arr['user_wage_count'] = $v['WageCount'];//UserWegeArr
                            $arr['proceeds_id'] = $MaxId;
							$row = DB::connection('mysql_other')->table('yl_wage_user')->insert($arr);
                        }
                        if($row){
                            return RequestBackController::Structure(601);
                        }
                    }else{
                        return RequestBackController::Structure(602);
                    }
              }   
                
            }else{//暂无权限
                return RequestBackController::Structure(504);
            }
            
        }
			
		

    }
	
	 /*
    单条收款流水详情
    */
    public function ShowGatheringById($request){
        if(!CheckController::CheckUser($request)){
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId','ProceedsId'])){//
            return RequestBackController::Structure(502);
        }else{
            $Purview = new PurviewController();
            $UserPurview = $Purview->PurviewVerdict($request,$pos['UserId']);
            if($UserPurview == 'All'){
                $findRow =  DB::connection('mysql_other')->table('yl_proceeds as p')->select('p.proceeds_id as ProceedsId','p.proceeds_count as ProceedsCount','p.proceeds_creater_id as ProceedsCreaterId','p.proceeds_created_time as ProceedsCreatedTime','p.case_id as CaseId','p.proceeds_results_id as ProceedsResultsId','p.proceeds_end_time as ProceedsEndTime','p.proceeds_end as ProceedsEnd','c.case_id as CaseId','c.case_title as CaseTitle','r.proceeds_results_id as ProceedsResultsId','r.proceeds_results_title as ProceedsResultsTitle','u.user_id as UserId','u.user_name as UserName','u.user_img as UserImg')
                                ->join("yl_proceeds_results as r",function($join){
                                    $join->on('p.proceeds_results_id','r.proceeds_results_id');
                                })
                                ->join("yl_case as c",function($join){
                                    $join->on('p.case_id','c.case_id');
                                })
                                ->join("yl_user as u",function($join){
                                    $join->on('p.proceeds_creater_id','u.user_id');
                                })
                                ->where('p.proceeds_id',$pos['ProceedsId'])
                                ->first();
                $wegeUser = DB::connection('mysql_other')->table('yl_wage_user as w')->select('w.user_wage_id as UserWageId','w.case_id as CaseId','w.user_id as UserId','w.user_wage_count as UserWageCount','w.proceeds_id as ProceedsId','u.user_id as UserId','u.user_name as UserName','u.user_img as UserImg')
                                                ->join("yl_user as u",function($join){
                                                    $join->on('w.user_id','u.user_id');
                                                })
                                                ->where('w.proceeds_id',$pos['ProceedsId'])
                                                ->get()->map(function ($val){
                                                                $val = (array)$val;
                                                                return $val;
                                                            })
                                                ->toArray();
					if($findRow){
						$findRow->ProceedsCreatedTime =date('Y-m-d',$findRow->ProceedsCreatedTime);
                        if($findRow->ProceedsEndTime == null || $findRow->ProceedsEndTime == ''){
                            $findRow->ProceedsEndTime= '--';
                        }else{
                            $findRow->ProceedsEndTime =date('Y-m-d',$findRow->ProceedsEndTime);
                        }
					}
					if($wegeUser){
						foreach($wegeUser as $k1 => $v1){
							$wegeUser[$k1]['UserWageId'] =$v1['UserWageId'];
							$wegeUser[$k1]['CaseId'] =$v1['CaseId'];
							$wegeUser[$k1]['UserPeoId'] =$v1['UserId'];
							$wegeUser[$k1]['UserWageCount'] =$v1['UserWageCount'];
							$wegeUser[$k1]['WageProceedsId'] =$v1['ProceedsId'];
							$wegeUser[$k1]['WageUserName'] =$v1['UserName'];
							$wegeUser[$k1]['WageUserImg'] =$v1['UserImg'];
						}
					}
						$row['TotalWege']=$findRow;
						$row['UserWege']=$wegeUser;
                if($row){
                    return RequestBackController::Structure(501,$row);
                }else{
                    return RequestBackController::Structure(504);
                }
               
            }else{
				return RequestBackController::Structure(504);
			}

        }

    }
  /*
    删除收款显示(当收款为已收款不能删除数据)
    */
     public function DeleteGatheringById($request){
        if (!CheckController::CheckUser($request)) {
            return RequestBackController::Structure(205);
        }
        $pos = $request->all();
        if(!CheckController::CheckParameter($pos,['UserId','ProceedsId'])){//
           return RequestBackController::Structure(502);
        }else{
            $Purview = new PurviewController();
            $UserPurview = $Purview->PurviewVerdict($request,$pos['UserId']);
            if($UserPurview == 'All'){//超级管理员
                $proceeds = DB::connection('mysql_other')->table('yl_proceeds')->where('proceeds_id',$pos['ProceedsId'])->first();
				//print_r($proceeds);die;
                if($proceeds->proceeds_end == 1){//完成收款不能删除
                    return RequestBackController::Structure(608);
                }else{//删除分成记录
                    $findRow =DB::connection('mysql_other')->table('yl_wage_user')->where('proceeds_id',$pos['ProceedsId'])->delete();
                    if($findRow){
                        $row = DB::connection('mysql_other')->table('yl_proceeds')->where('proceeds_id',$pos['ProceedsId'])->delete();
                        if($row){
                            return RequestBackController::Structure(601);
                        }else{
                            return RequestBackController::Structure(602);
                        }
                    }else{
                        return RequestBackController::Structure(602);
                    }
                }
            }else{
                //无权限
                return RequestBackController::Structure(403);
            }
       }
        
    }
	/*
	确认到账
    */
    public function AffirmGathering($request){
        if (!CheckController::CheckUser($request)) {
            return RequestBackController::Structure(205);
        }
        $pos = $request->all();
        if(!CheckController::CheckParameter($pos,['UserId','ProceedsId'])){//
           return RequestBackController::Structure(502);
        }else{
            $Purview = new PurviewController();
            $UserPurview = $Purview->PurviewVerdict($request,$pos['UserId']);
            if($UserPurview == 'All'){
                $ProceedsId = DB::connection('mysql_other')->table('yl_proceeds')->where('proceeds_id',$pos['ProceedsId'])->first();
                if($ProceedsId){
                    if($ProceedsId->proceeds_results_id ==1){//当收款信息已经为确认收款。不能点击确认收款按钮
                        return RequestBackController::Structure(602);
                    }else{
                        $map =array();
                        $map['proceeds_results_id']=1;//确认收款
                        $map['proceeds_end_time'] = time();
                        $map['proceeds_end'] = 1;//完成收款
                        $row = DB::connection('mysql_other')->table('yl_proceeds')->where('proceeds_id',$pos['ProceedsId'])->update($map);
                        if($row){
                            return RequestBackController::Structure(601);
                        }else{
                            return RequestBackController::Structure(602);
                        }
                    }

                }else{
                    return RequestBackController::Structure(505);
                }
            }else{
                //无权限
                return RequestBackController::Structure(403);
            }
            
        }

    }
	/*
    单条收款编辑
    */
    public function EditGatheringById($request){
        if(!CheckController::CheckUser($request)){
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['UserId','ProceedsId','ProceedsCount','wegeArr'])){//
            return RequestBackController::Structure(502);
        }else{
            $Purview = new PurviewController();
            $UserPurview = $Purview->PurviewVerdict($request,$pos['UserId']);
            if($UserPurview == 'All'){
                $findRow =  DB::connection('mysql_other')->table('yl_proceeds')->where('proceeds_id',$pos['ProceedsId'])->first();
                if($findRow->proceeds_results_id == 1){//该条收款已确定无法修改
                    return RequestBackController::Structure(609);
                }else{
                    $map = array();
                    $map['proceeds_count'] =$pos['ProceedsCount'];
                    $upRow = DB::connection('mysql_other')->table('yl_proceeds')->where('proceeds_id',$pos['ProceedsId'])->update($map);
                    $arr=array();
                    foreach ($pos['wegeArr'] as $k => $v) {
                        $arr['user_wage_count'] = $v['UserWageCount'];
                        $arr['user_id'] = $v['UserId'];
                        $row = DB::connection('mysql_other')->table('yl_wage_user')
                                                            ->where('proceeds_id',$pos['ProceedsId'])
                                                            ->where('user_wage_id',$v['UserWageId'])
                                                            ->update($map);
                        
                    }
                    if($row){
                        return RequestBackController::Structure(601);
                    }else{
                        return RequestBackController::Structure(602);
                    }

                }

            }

        }

    }


   
}